package com.itheima;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import org.junit.Test;

import java.util.HashMap;


/*
    Json使用 测试类
* */
public class JsonDemo {

    ObjectMapper mapper= new ObjectMapper();

    @Test
    public void test01() throws Exception {
        //User转json
        User user = new User("张三", 23);
        String json = mapper.writeValueAsString(user);
        System.out.println("json字符串: " + json);

        //json转user
        User user1 = mapper.readValue(json, User.class);
        System.out.println("java对象: " +user1);
    }

    @Test
    public void test02() throws Exception {
        //map<String,String>转json
        HashMap<String,String> map = new HashMap<>();
        map.put("张三","23");
        map.put("李四","24");
        String json = mapper.writeValueAsString(map);
        System.out.println(json);

        //转回来
        System.out.println(mapper.readValue(json,HashMap.class));;
    }


    @Test
    public void test03() throws Exception{
        //map<String,User>转json
        HashMap<String,User> map = new HashMap<>();
        map.put("黑马一班",new User("张三",23));
        map.put("黑马二班",new User("李四",24));
        String json = mapper.writeValueAsString(map);
        System.out.println(json);

        //转回来
        HashMap<String,User> map1 = mapper.readValue(json,new TypeReference<HashMap<String,User>>(){});
        System.out.println(map1);


    }

}
